package com.cloudkinto.service.qianyi.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.cloudkinto.common.BeanConvert;
import com.cloudkinto.common.DicBusinessConstant;
import com.cloudkinto.common.DicBusinessItemConstant;
import com.cloudkinto.common.exception.BizException;
import com.cloudkinto.common.web.PageInfo;
import com.cloudkinto.common.web.PageResult;
import com.cloudkinto.common.web.SingleResult;
import com.cloudkinto.dao.*;
import com.cloudkinto.entity.*;
import com.cloudkinto.extentity.StockRecordNewDto;
import com.cloudkinto.service.orderoutput.OrderOutputService;
import com.cloudkinto.service.orderoutput.openapivo.OpenApiOrderOutputAddReq;
import com.cloudkinto.service.orderoutput.openapivo.OpenApiOrderOutputProductAddReq;
import com.cloudkinto.service.orderoutput.vo.OrderOutputDetailRes;
import com.cloudkinto.service.qianyi.QianyiErpService;
import com.cloudkinto.service.qianyi.vo.*;
import com.cloudkinto.service.stock.StockRecordService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.function.Consumer;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * Author Administrator
 *
 * @Des
 * @Version
 * @Date 2021/9/30
 */
@Slf4j
@Service
public class QianyiErpServiceImpl extends ServiceImpl<OrderOutputDao, OrderOutputDo> implements QianyiErpService {

    private static final String QIANYI = "qianyi";
    @Autowired
    private ShopDao shopDao;
    @Autowired
    private CompanyDao companyDao;
    @Autowired
    private StorageDao storageDao;
    @Autowired
    private DicBusinessItemDao dicBusinessItemDao;
    @Autowired
    private OrderOutputService orderOutService;
    @Autowired
    private StockRecordService stockRecordService;

    private Long userId = 229L;//千易专属userId

    @Override
    public QianyiResponse comPost(QianyiErpRequest request) {
        LambdaQueryWrapper<ShopDo> shopDoLambdaQueryWrapper = new LambdaQueryWrapper<>();
        shopDoLambdaQueryWrapper.eq(ShopDo::getQainyiAccessId, request.getAccessId());
        ShopDo shopDo = shopDao.selectOne(shopDoLambdaQueryWrapper);
        Long companyId = 0L;
        if (shopDo == null) {
            CompanyDo companyDo = companyDao.selectOne(new LambdaQueryWrapper<CompanyDo>().eq(CompanyDo::getCompanyCode, request.getAccessId()));
            if (companyDo != null) {
                companyId = companyDo.getId();
            }
        } else {
            companyId = shopDo.getCompanyId();
        }
        log.debug((request.toString()));
//        ShopDo shopDo = shopDao.selectById(33);
        if (companyId == 0) return QianyiResponse.failue("不存在该用户的绑定信息");
        if ("getOrder".equals(request.getMethod())) {
            return getOrder(JSON.parseObject(request.getContent()).getString("orderNumber"), companyId);
        } else if ("createOrder".equals(request.getMethod())) {
            return createOrder(request, companyId);
        } else if ("channels".equals(request.getMethod())) {
            return QianyiResponse.channelSuccess(getChannels());
        } else if ("warehouses".equals(request.getMethod())) {
            return QianyiResponse.warehoseSuccess(getWarehouses());
        } else if ("cancelOrder".equals(request.getMethod())) {
            return cancelOrder(JSON.parseObject(request.getContent()).getString("orderNumber"), companyId);
        } else if ("syncInventory".equals(request.getMethod())) {
            return syncInventory(request.getContent(), companyId);
        } else {

        }
        return null;
    }

    private QianyiResponse syncInventory(String content, Long companyId) {
        QianyiInventoryRequest request = JSON.parseObject(content, QianyiInventoryRequest.class);
        Map<String, String> map = new HashMap<>();
        map.put("current", request.getPage());
        map.put("pageSize", request.getPageSize());
        map.put("companyId", companyId + "");
        if (StringUtils.isNotBlank(request.getWarehouseCode())) {
            StorageDo storageDo = storageDao.selectOne(new LambdaQueryWrapper<StorageDo>()
                    .eq(StorageDo::getCode, request.getWarehouseCode()));
            if (storageDo == null) return QianyiResponse.failue("仓库不存在");
            map.put("storageId", storageDo.getId() + "");
        }
        map.put("keyword", request.getWarehouseSku());
        PageResult<StockRecordNewDto> listPage = stockRecordService.getStockListGroupCompany(map);
        Collection<StockRecordNewDto> values = listPage.getValues();
        List<QianyiInventoryResponse> collect = values.stream().map(new Function<StockRecordNewDto, QianyiInventoryResponse>() {
            @Override
            public QianyiInventoryResponse apply(StockRecordNewDto stockRecordPageRes) {
                QianyiInventoryResponse response = new QianyiInventoryResponse();
                response = BeanConvert.INSTANCE.stockRecordNew2QainyiInventory(stockRecordPageRes);
                response.setSellableQuantity(String.valueOf(stockRecordPageRes.getCanSellCount() - stockRecordPageRes.getToSend()));
                response.setTotalQuantity(String.valueOf(stockRecordPageRes.getCanSellCount() + stockRecordPageRes.getCanotSellCount()));
                return response;
            }
        }).collect(Collectors.toList());
        PageInfo pageInfo = listPage.getPageInfo();

        QianyiPageResponse<List<QianyiInventoryResponse>> success = QianyiPageResponse.success(pageInfo.getCurrent() == pageInfo.getPageNos(),
                pageInfo.getCurrent(), pageInfo.getPageSize(), collect);
        log.debug(JSON.toJSONString(collect));
        return success;
    }

    private QianyiResponse getOrder(String orderNumber, Long companyId) {
        OrderOutputDetailRes orderOutputDetailRes;
        QianyiOrderInfoResponse response = new QianyiOrderInfoResponse();
        LambdaQueryWrapper<OrderOutputDo> orderOutputDoLambdaQueryWrapper = new LambdaQueryWrapper<>();
        orderOutputDoLambdaQueryWrapper.eq(OrderOutputDo::getPlatformNumber, orderNumber);
        orderOutputDoLambdaQueryWrapper.eq(OrderOutputDo::getPlatform, QIANYI);
        orderOutputDoLambdaQueryWrapper.eq(OrderOutputDo::getCompanyId, companyId);
        orderOutputDoLambdaQueryWrapper.last("order by id desc limit 1");
        try {
            OrderOutputDo orderOutputDo = orderOutService.getBaseMapper().selectOne(orderOutputDoLambdaQueryWrapper);
            if (orderOutputDo == null) {
                orderOutputDo = new OrderOutputDo();
                orderOutputDo.setPlatformNumber(orderNumber);
                orderOutputDo.setStatus(0L);
            }
//            orderOutputDetailRes = orderOutService.getTrackInfo(orderOutputDo.getOrderOutputNumber(), companyId);
            response.setOrderNumber(orderOutputDo.getPlatformNumber());
            DicBusinessItemDo itemDo = dicBusinessItemDao.selectById(orderOutputDo.getStatus());
            if (itemDo != null)
                response.setWmsStatus(itemDo.getDicItemValue());
            DicBusinessItemDo itemDoTrack = dicBusinessItemDao.selectById(orderOutputDo.getTrackId());
            if (itemDoTrack != null)
                response.setCarrierName(itemDoTrack.getDicItemValue().replaceAll("[a-zA-Z]", ""));
            response.setTrackingNumber(orderOutputDo.getTrackNumber());
            if (orderOutputDo.getStatus() == 0L) {
                response.setWmsStatus("已删除");
                response.setStatus("FAILED");
                response.setFailedReason(orderNumber + "订单号不存在或已被删除");
            } else if (orderOutputDo.getStatus() == DicBusinessItemConstant.outCreateState.intValue()) {
                response.setStatus("FAILED");
                response.setFailedReason("订单异常,具体原因请咨询客服");
            } else if (orderOutputDo.getStatus() < DicBusinessItemConstant.outSendOut ||
                    DicBusinessItemConstant.waitingPickUp.equals(orderOutputDo.getStatus()) ||
                    DicBusinessItemConstant.alreadyPickUp.equals(orderOutputDo.getStatus()) ||
                    DicBusinessItemConstant.outWaitCheckOut.equals(orderOutputDo.getStatus())) {
                response.setStatus("SENDING");
            } else if (orderOutputDo.getStatus() <= DicBusinessItemConstant.outPushError || orderOutputDo.getStatus() == DicBusinessItemConstant.problemShipment) {
                response.setStatus("SUCCESS");
            } else if (orderOutputDo.getStatus() == DicBusinessItemConstant.outHasRecovered.intValue() ||
                    orderOutputDo.getStatus() == DicBusinessItemConstant.orderCutOff.intValue()) {
                response.setStatus("CANCEL");
            }
        } catch (BizException e) {
            e.printStackTrace();
            return QianyiResponse.failue(e.getErrorMsg());
        } catch (Exception e1) {
            e1.printStackTrace();
            return QianyiResponse.failue(e1.getMessage());
        }
        return QianyiResponse.success(response);
    }

    private QianyiResponse cancelOrder(String orderNumber, Long companyId) {
        LambdaQueryWrapper<OrderOutputDo> orderOutputDoLambdaQueryWrapper = new LambdaQueryWrapper<>();
        orderOutputDoLambdaQueryWrapper.eq(OrderOutputDo::getPlatformNumber, orderNumber);
        orderOutputDoLambdaQueryWrapper.eq(OrderOutputDo::getPlatform, QIANYI);

        orderOutputDoLambdaQueryWrapper.and(new Consumer<LambdaQueryWrapper<OrderOutputDo>>() {
            @Override
            public void accept(LambdaQueryWrapper<OrderOutputDo> orderOutputDoLambdaQueryWrapper1) {
                orderOutputDoLambdaQueryWrapper1.eq(OrderOutputDo::getStatus, DicBusinessItemConstant.outCreateCheckState).or()
                        .eq(OrderOutputDo::getStatus, DicBusinessItemConstant.outWaitSendOut).or()
                        .eq(OrderOutputDo::getStatus, DicBusinessItemConstant.outWaitCheckOut).or()
                        .eq(OrderOutputDo::getStatus, DicBusinessItemConstant.alreadyPickUp).or()
                        .eq(OrderOutputDo::getStatus, DicBusinessItemConstant.waitingPickUp);
            }
        });
        orderOutputDoLambdaQueryWrapper.eq(OrderOutputDo::getCompanyId, companyId);

        SingleResult result;
        try {
            OrderOutputDo orderOutputDo = orderOutService.getBaseMapper().selectOne(orderOutputDoLambdaQueryWrapper);
            result = orderOutService.cancelOrder(orderOutputDo.getOrderOutputNumber(), userId);

        } catch (BizException e) {
            e.printStackTrace();
            return QianyiResponse.failue(e.getErrorMsg());
        } catch (Exception e) {
            e.printStackTrace();
            return QianyiResponse.failue(e.getMessage());
        }
        if ("200".equals(result.getCode())) {
            return QianyiResponse.success();
        } else {
            return QianyiResponse.failue(result.getMessage());
        }
    }

    private QianyiResponse createOrder(QianyiErpRequest request, Long companyId) {
        QianyiCreateOutOrderReq entity = JSON.parseObject(request.getContent(), QianyiCreateOutOrderReq.class);
        OpenApiOrderOutputAddReq outputAddReq = new OpenApiOrderOutputAddReq();
        if (StringUtils.isNotBlank(entity.getWarehouseCode())) {
            LambdaQueryWrapper<StorageDo> storageWrapper = new LambdaQueryWrapper<>();
            storageWrapper.eq(StorageDo::getCode, entity.getWarehouseCode());
            storageWrapper.eq(StorageDo::getCountryType, 1);
            StorageDo storageDo = storageDao.selectOne(storageWrapper);
            if (storageDo == null) return QianyiResponse.failue("仓库代码不存在");
            outputAddReq.setStorageId(storageDo.getId());
        }
        ShopDo shopDo = shopDao.selectOne(new LambdaQueryWrapper<ShopDo>().eq(ShopDo::getCompanyId, companyId).eq(ShopDo::getQianyiShopName, entity.getShopName()));
        if (shopDo == null) {
            List<ShopDo> shopDoList = shopDao.selectList(new LambdaQueryWrapper<ShopDo>().eq(ShopDo::getCompanyId, companyId));
            if (shopDoList.size() == 1) {
                shopDo = shopDoList.get(0);
            }
        }
        if (shopDo != null) {
            outputAddReq.setShopId(shopDo.getId());
        } else {
            return QianyiResponse.failue("请先绑定千易店铺");
        }
        outputAddReq.setOrderNo(entity.getOnlineOrderId());
        outputAddReq.setPlatformNumber(entity.getOrderNumber());
        outputAddReq.setPlatform(QIANYI);

        outputAddReq.setTrackId(getTrackIdByCode(entity.getLogisticsCode()));
        outputAddReq.setSendDate(new Date());
        outputAddReq.setReceiverName(entity.getReceiver().getName());
        outputAddReq.setTelPhone(entity.getReceiver().getPhone());
        outputAddReq.setArea(entity.getReceiver().getState());
        outputAddReq.setAddress((entity.getReceiver().getCity() == null ? "" : entity.getReceiver().getCity()) + (entity.getReceiver().getDistrict() == null ? "" : entity.getReceiver().getDistrict()) + (entity.getReceiver().getAddress1() == null ? "" : entity.getReceiver().getAddress1()) + (entity.getReceiver().getAddress2() == null ? "" : entity.getReceiver().getAddress2()));
        outputAddReq.setPostCode(entity.getReceiver().getPostalCode());
        List<OpenApiOrderOutputProductAddReq> productAddReqList = new ArrayList<>();
        entity.getSkuList().stream().forEach(qainyiSkuListEntity -> {
            OpenApiOrderOutputProductAddReq productAddReq = new OpenApiOrderOutputProductAddReq();
            productAddReq.setCount(qainyiSkuListEntity.getQuantity());
            productAddReq.setCommoditySku(qainyiSkuListEntity.getSku());
            productAddReqList.add(productAddReq);
        });
        outputAddReq.setProductList(productAddReqList);
//        outputAddReq.setOrderNo(entity.getOnlineOrderId());
        SingleResult result = null;
        try {
            log.info(JSON.toJSONString(outputAddReq));
            result = orderOutService.openApiAdd(outputAddReq, companyId, userId, false);
        } catch (BizException e) {
            e.printStackTrace();
            return QianyiResponse.failue(e.getErrorMsg());
        } catch (Exception e) {
            e.printStackTrace();
            return QianyiResponse.failue(e.getMessage());
        }
        if ("200".equals(result.getCode())) {
            return QianyiResponse.success();
        } else {
            return QianyiResponse.failue(result.getMessage());
        }
    }


    private List<Map> getChannels() {
        LambdaQueryWrapper<DicBusinessItemDo> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(DicBusinessItemDo::getDicBusinessId, DicBusinessConstant.trackCompany);
        List<DicBusinessItemDo> trackCompanyList = dicBusinessItemDao.selectList(wrapper);
        List<Map> list = new ArrayList<>();
        List<Map> collect = trackCompanyList.stream().filter(itemDo -> itemDo.getId() < 44).map(itemDo -> {
            Map map = new HashMap();
            map.put("channelCode", getTrackCode(itemDo.getId()));
            map.put("channelName", itemDo.getDicItemValue());
            map.put("carrierName", itemDo.getDicItemValue().replaceAll("[a-zA-Z]", ""));
            return map;
        }).collect(Collectors.toList());
//        Map map = new HashMap();
//        map.put("channelCode", 0);
//        map.put("channelName", "自动选择");
//        map.put("carrierName", "");
//        list.add(map);
        list.addAll(collect);
        return list;
    }

    private List<Map> getWarehouses() {
        QueryWrapper wrapper = new QueryWrapper();
        wrapper.eq("country_type", 1);
        wrapper.orderByDesc("id");
        List<StorageDo> storageDoList = storageDao.selectList(wrapper);
        return storageDoList.stream().map(storageDo -> {
            Map map = new HashMap();
            map.put("warehouseCode", storageDo.getCode());
            map.put("warehouseName", storageDo.getStorageName());
            return map;
        }).collect(Collectors.toList());
    }

    private String getTrackCode(Long trackId) {
        if (trackId == DicBusinessItemConstant.sagawaExpress) {
            return "Sagawa";
        } else if (trackId == DicBusinessItemConstant.yamatoExpress || trackId.equals(DicBusinessItemConstant.yamatoExpressSmall) || trackId.equals(DicBusinessItemConstant.yamatoExpressBox)) {
            return "Yamato";
        } else if (trackId == DicBusinessItemConstant.xinongExpress) {
            return "SEINO";
        } else if (trackId == DicBusinessItemConstant.jpostExpress) {
            return "JPOST";
        }
        return "";
    }

    private Long getTrackIdByCode(String logisticsCode) {
        if ("Sagawa".equals(logisticsCode)) {
            return DicBusinessItemConstant.sagawaExpress;
        } else if ("Yamato".equals(logisticsCode)) {
            return DicBusinessItemConstant.yamatoExpress;
        } else if ("SEINO".equals(logisticsCode)) {
            return DicBusinessItemConstant.xinongExpress;
        } else if ("JPOST".equals(logisticsCode)) {
            return DicBusinessItemConstant.jpostExpress;
        }
        return null;
    }

}
